<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2018/12/17
 * Time: 16:08
 */
namespace app\api\controller;
use think\Cache;
use think\Db;
use think\Session;

class Timer extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {

    }
    public function dowload() {//echo 1;die;
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
        if(strpos($agent, 'iphone') || strpos($agent, 'ipad'))
        {
            echo "<script> location.href='http://wap.yunping168.com'; </script>";
            // echo ' ios 下载地址';
        }else{
            echo "<script> location.href='https://a.app.qq.com/o/simple.jsp?pkgname=com.yunping.app&scenevia=WXFUWUHAO-CAIDAN-1&g_f=1115331'; </script>";
            // echo ' Android 下载地址';
        }

    }
    /**
     * 定时器：任务状态更改和用户认领状态更改
     */
    public function checkTaskStatus(){
        set_time_limit(0);
        $tasktype = ['error','下载','求赞求粉','问卷','投票','视频','分享'];
        $today = date('Y-m-d H:i:s');
        $two_days_ago = date("Y-m-d H:i:s",(strtotime("{$today}")-3600*24*2));
        //1、把未开始的符合开始条件的改为开始
        Db::name('task')
            ->where('task_starttime','<=',$today)
            ->where('task_endtime','>',$today)
            ->where('task_status',1)
            ->where('task_active_status',2) // 活动任务得是通过的
            ->where('task_super',2) // 达人任务也得是通过的
            ->update (['task_status'=>2]);
        //2、把开始的符合到期条件的改为到期(同时把剩余的币还给商家)
        $field = 'task_s_id,task_price,task_num,task_done_num,task_type';
        $field .= ',task_share_type,task_share_d_fen,task_share_d_fen_money';
        $field .= ',task_active,task_super_first_money,task_super_admin_money,task_id,task_money';
        $xia = Db::name('task')
            ->where('task_starttime','<=',$today)
            ->where('task_endtime','<=',$today)
            ->where('task_status',2)
            ->where('task_active_status',2)
            ->where('task_super',2)
            ->field ($field)
            ->select();
        if($xia){
            foreach ($xia as $k=>$v){
                if($v['task_num'] > $v['task_done_num']){
                    if($v['task_active'] == 3){
                        $drstainfo = Db::name('task_user')->where('tu_task_id',$v['task_id'])->field('tu_status,tu_super_yes')->find();
                        $drsta = $drstainfo['tu_status'];
                        if($drstainfo['tu_super_yes'] != 2){
                            $back = $v['task_price'];
                            Db::name('task_user')->where('tu_task_id',$v['task_id'])->setField('tu_status',7);
                        }else{
                            if($drsta == 2){
                                $back = 0;
                            }else{
                                $back = $v['task_price'] - $v['task_super_first_money'] - $v['task_super_admin_money'];
                            }
                        }

                    }else{
                        $back = ($v['task_num'] - $v['task_done_num'])*$v['task_price'];
                        //-分享的到达的分步骤任务比较特殊-start
                        if($v['task_type'] == 6 && $v['task_share_type'] == 2 && $v['task_share_d_fen'] == 2){
                            $back = $v['task_money'] - $v['task_share_d_fen_money'];
                        }
                        //-分享的到达的分步骤任务比较特殊-end
                    }

                    if($back > 0){
                        Db::name('shops')
                            ->where('s_id',$v['task_s_id'])
                            ->setInc('s_money',$back);
                        //入商户明细和商户消息
                        allInShopDetail($back,2,$v['task_s_id'],$tasktype[$v['task_type']].'任务结束退还');
                        allInNotice('任务结束退还',$tasktype[$v['task_type']].'任务结束退还，返还'.($back/10).'元！',3,$v['task_s_id']);
                    }
                }
            }
            Db::name('task')
                ->where('task_starttime','<=',$today)
                ->where('task_endtime','<=',$today)
                ->where('task_status',2)
                ->where('task_active_status',2)
                ->where('task_super',2)
                ->update (['task_status'=>3]);
        }
        //3、把用户领的任务改超时改成超时（同时减少任务的领取量）
        $data = Db::name('task_user tu')
            ->join ('task t','tu.tu_task_id = t.task_id','LEFT')
            ->where('tu_real_time','<=',$two_days_ago)
            ->where('tu_status','in','3,4')
            ->where('tu_task_active','in','1,2') // 达人要单独做判断
            ->where('task_status',2) //其他的没有减少的必要
            ->where('task_share_d_fen',1) //分享分步骤的和其他要区分开
            ->group('tu_task_id')
            ->field('tu_task_id,count(*) as num')
            ->select();
        if($data){
            foreach ($data as $k=>$v){
                Db::name('task')
                    ->where('task_id',$v['tu_task_id'])
                    ->setDec('task_get_num',$v['num']);
            }
            //除了减少数量的，其他状态的都是超时（应该放外面吧）
//            Db::name('task_user')
//                ->where('tu_real_time','<=',$two_days_ago)
//                ->where('tu_status','in','3,4')
//                ->update (['tu_status'=>7]);
        }
        Db::name('task_user tu')
            ->join ('task t','tu.tu_task_id = t.task_id','LEFT')
            ->where('tu_real_time','<=',$two_days_ago)
            ->where('tu_status','in','3,4')
            ->where('tu_task_active','in','1,2')  // 达人要单独更新
            ->where('task_share_d_fen',1) //分享分步骤的和其他要区分开
            ->update (['tu_status'=>7]);
        //达人超时！！！TODO：时间
        $jit = Db::table('up_about_us')->where('about_id',1)->value('super_time');
        $dr_days_ago = date("Y-m-d H:i:s",(strtotime("{$today}")-3600*$jit));
        $datadr = Db::name('task_user tu')
            ->join ('task t','tu.tu_task_id = t.task_id','LEFT')
            ->where('tu_real_time','<=',$dr_days_ago)
            ->where('tu_status','in','3,4')
            ->where('tu_task_active',3) // 达人要单独做判断
            ->where('tu_super_yes',2)  //没接的不算
            ->field('tu_task_id,task_type,task_lock,task_price,task_super_first_money,task_super_admin_money,tu_user_id,tu_s_id')
            ->select();
        if($datadr){
            foreach ($datadr as $k=>$v){
                $user_id = $v['tu_user_id'];
                $task_id = $v['tu_task_id'];
                //退还商户先给的那一部分(含抽佣)，并减掉用户的（是锁定的还是非锁定的）
                Db::name('shops')->where('s_id',$v['tu_s_id'])->setInc ('s_money',$v['task_super_first_money']+$v['task_super_admin_money']);
                allInShopDetail($v['task_super_first_money']+$v['task_super_admin_money'],2,$v['tu_s_id'],$tasktype[$v['task_type']].'达人任务结束退还');
                allInNotice('达人任务结束退还',$tasktype[$v['task_type']].'达人任务结束退还，返还'.(($v['task_super_first_money']+$v['task_super_admin_money'])/10).'元！',3,$v['tu_s_id']);
                //减用户的
                if($v['task_lock'] == 1){
                    Db::name('u_user')->where('user_id',$user_id)->setDec('user_super_no',$v['task_super_first_money']);
                }else{
                    $error = Db::name('u_user')->where('user_id',$user_id)->value('user_all_money');
                    if($error-$v['task_super_first_money'] < 0){
                        Db::name('task')->where('task_id',$task_id)->setField('task_super_error',$v['task_super_first_money']-$error);
                    }
                    Db::name('u_user')->where('user_id',$user_id)->setDec ('user_week_money',$v['task_super_first_money']);
                    Db::name('u_user')->where('user_id',$user_id)->setDec ('user_month_money',$v['task_super_first_money']);
                    Db::name('u_user')->where('user_id',$user_id)->setDec ('user_all_money',$v['task_super_first_money']);
                }
                allInDetail($user_id,2,$tasktype[$v['task_type']].'达人任务',$v['task_super_first_money'],$v['task_type'],3);
            }
        }
        Db::name('task_user tu')
            ->where('tu_real_time','<=',$dr_days_ago)
            ->where('tu_status','in','3,4')
            ->where('tu_task_active',3)  // 达人要单独更新
            ->where('tu_super_yes',2)  //没接的不算
            ->update (['tu_status'=>7]);
        //-----------单独处理分享的分步骤的---------
        $dataF = Db::name('task_user tu')
            ->join ('task t','tu.tu_task_id = t.task_id','LEFT')
            ->where('tu_status','in','3,4')
            ->where('task_status','in','2,3,4') //只有2，其他的没有减少的必要，1和5没有超时的必要
            ->where('task_share_d_fen',2) //分享分步骤的和其他要区分开
            ->field('tu_task_id,tu_id,tu_share_fen,tu_status,tu_real_time,task_status,task_share_timeout')
            ->select();
        if($dataF){
            foreach ($dataF as $kk=>$vv){
                $day_timeout = date("Y-m-d H:i:s",(strtotime("{$today}")-3600*$vv['task_share_timeout']));
                //先把进行中的只是第一步的超时的任务数量还回去
                if($vv['task_status'] == 2 && $vv['tu_share_fen'] == 1 && $vv['tu_real_time'] <= $day_timeout){
                    Db::name('task')
                        ->where('task_id',$vv['tu_task_id'])
                        ->setDec('task_get_num',1);
                }
                //再把其他的只要超时的任务改成超时
                if($vv['tu_real_time'] <= $day_timeout){
                    Db::name('task_user')
                        ->where('tu_id',$vv['tu_id'])
                        ->update (['tu_status'=>7]);
                }
            }
        }
        return true;
    }
    /**
     * 定时器：每天0点清空相应的数据
     * @return bool
     */
    public function dayAndMonth()
    {
        set_time_limit(0);
        $w = date('w');
        $d = date('d');
        if($w == 1){
            //说明今天是这个礼拜的第一天
            Db::table ('up_u_user')->where('user_id','>',0)->setField('user_week_money',0);
        }
        if($d == 1){
            //说明今天是这个月的第一天
            Db::table ('up_u_user')->where('user_id','>',0)->setField('user_month_money',0);
        }
        return true;
    }
    /**
     * 定时器：每分钟查询一次的极光推送和消息(用户即将超时和商户即将超时)
     * @return bool
     */
    public function pushMinute()
    {
        set_time_limit(0);
        $today = date('Y-m-d H:i:s');
        $one_hour_after = date("Y-m-d H:i:s",(strtotime("{$today}")+3600));
        //1、商户的快超时》消息表
        $shops = Db::name('task')
            ->where('task_endtime','<=',$one_hour_after)
            ->where('task_status',2)
            ->where('task_active_status',2)
            ->where('task_push',1)
            ->field('task_name,task_s_id,task_id')
            ->select();
        if($shops){
            foreach($shops as $k=>$v){
                $sid = $v['task_s_id'];
                Db::name('task')->where('task_id',$v['task_id'])->setInc('task_push');
                allInNotice('任务到期提示','尊敬的商户您好，您发布的 ' . $v['task_name'] . ' 任务还有一小时就截止了，请知悉！',3,$sid);
            }
        }
        //2、用户的快超时》推送
        $users = Db::name('task_user tu')
            ->join ('task t','tu.tu_task_id = t.task_id','LEFT')
            ->where('tu_real_time','<=',$one_hour_after)
            ->where('tu_status','in','3,4')
            ->where('tu_push',1)
//            ->group ('tu_s_id')
            ->field('task_name,tu_user_id,tu_id')
            ->select();
        if($users){
            foreach($users as $k=>$v){
                $uid = (string)$v['tu_user_id'];
                try{
                    Db::name('task_user')->where('tu_id',$v['tu_id'])->setInc('tu_push');
                    $this->Jpush(1, $uid, '亲～你领取的 ' . $v['task_name'] . ' 任务即将超时，赶快去看看>>', array('s_u'=>1));
                }catch(\Exception $e){

                }
            }
        }
        return true;
    }

    /**
     * 微博第三方登录——获取用户id和信息
     * @return \think\response\Json
     */
    public function aaaaaa()
    {
        header("Access-Control-Allow-Origin: *");
        $code = $_REQUEST['code'];
        $body_json = array(
            'client_id' => '1228667031',
            'client_secret' => '2363c310edc1c847fa80a4feedcb211b',
            'grant_type' => 'authorization_code',
            'code' => $code,
            'redirect_uri' => 'http://wap.yunping168.com/html/login_win.html'
        );
        $body = json_encode($body_json);
        $header = array(
            'Accept:application/json',
            'Content-Type:application/json;charset=utf-8',
        );
        //$url = 'https://api.weibo.com/oauth2/access_token';
        $url = 'https://api.weibo.com/oauth2/access_token?client_id=1228667031&client_secret=2363c310edc1c847fa80a4feedcb211b&grant_type=authorization_code&redirect_uri=http://wap.yunping168.com/html/login_win.html&code=' . $code;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result, true);
        if(isset($res['error'])){
            return json($res);
        }else{
            $res2 = $this->bbbbbb($res['access_token'],$res['uid']);
            return json($res2);
        }
    }

    public function bbbbbb($access_token,$uid)
    {
        $url="https://api.weibo.com/2/users/show.json?access_token=$access_token&uid=$uid";
        $ch = curl_init();
//            //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
//            //执行并获取HTML文档内容========
        $output = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($output, true);
        return $res;
    }
    public function abc(){
//        $num = substr(base_convert(md5(uniqid(md5(microtime(true)),true)), 16, 10), 0, 8);
//        $num = Qrcode('id=1&type=2',ROOT_PATH . 'public' . DS . 'uploads/ercode/20200327/274fc506eea629ec0fbed708bc691ff.png');
        $time = time();
        $one_hour_ago = date("Y-m-d",($time + 3600*24*7));
        $a = '2020-03-28';
        $b = '2020-03-28 12:12:12';
        if($a > $b){
            echo 1;
        }else{
            echo 0;
        }
        die;
        echo $one_hour_ago;die;
//        $code = GetRandCode();//6位数验证码
//        $templateid = config('yzx')['templateid'];
//        $sendres = YzxSms($code, '0085366260900', $templateid);//发送验证码
//        dump($sendres);
    }
}